package com.tanhua.server.service;

import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.commons.templates.OssTemplate;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.mongo.Visitor;
import com.tanhua.domain.vo.MomentVo;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.PublishVo;
import com.tanhua.domain.vo.VisitorVo;
import com.tanhua.dubbo.api.PublishApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VisitorApi;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.utils.RelativeDateFormat;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Classname MomentService
 * @Description TODO 动态业务类
 * @Date 2021/3/10 21:18
 * @Created by gan
 */
@Service
@Slf4j
public class MomentService {
    @Autowired
    private OssTemplate ossTemplate;

    @Reference
    private PublishApi publishApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate redisTemplate;

    @Reference
    private VisitorApi visitorApi;
    //发布动态
    public void postMoment(PublishVo vo, MultipartFile[] imageContent) {
        log.info("开始发布动态.............");
        //获取登录用户id
        Long userId = UserHolder.getUserId();
        log.info("登陆用户的id={}", userId);
        //遍历循环上传图片
        List<String> imageUrls=new ArrayList<String>();
        if(imageContent!=null){
            try {
                for (MultipartFile file : imageContent) {
                    String url = ossTemplate.upload(file.getOriginalFilename(), file.getInputStream());
                    log.info("上传的图片：{}",url);
                    imageUrls.add(url);

                }
            } catch (Exception e) {
                throw new TanHuaException("上传图片失败");
            }
        }
        //构建publish对象
        Publish publish=new Publish();
        BeanUtils.copyProperties(vo,publish);
        publish.setUserId(userId);
        publish.setMedias(imageUrls);
        log.info("动态的详情: {}", publish);
        // 调用服务发布动态
        publishApi.add(publish);
        log.info("发布动态成功...........");
    }


    //查询好友动态
    public PageResult<MomentVo> queryFriendPublishList(Long page, Long pagesize) {
        //获取登录用户id
        Long userId = UserHolder.getUserId();
        PageResult pageResult = publishApi.findFriendPublishByTimeline(page,pagesize,userId);
        //获取查询的结果集(动态的结果)
        List<Publish> publishList=pageResult.getItems();
        //遍历结果集
        //构建vo
        List<MomentVo> voList=new ArrayList<MomentVo>();
        if(publishList!=null){
            for (Publish publish : publishList) {
                Long publishId = publish.getUserId();
                //查询好友的详情
                UserInfo userInfo=userInfoApi.findByUserId(publishId);
                MomentVo vo=new MomentVo();
                //复制用户详情
                BeanUtils.copyProperties(userInfo,vo);
                vo.setTags(StringUtils.split(userInfo.getTags(),","));
                // 设置动态的id
                vo.setId(publish.getId().toHexString());
                // 默认距离
                vo.setDistance("100米");
                String key1 = "publish_like_" + userId+"_" + vo.getId();
                if(redisTemplate.hasKey(key1)){
                    vo.setHasLiked(1);  //是否点赞  0：未点 1:点赞
                }
                else
                {
                    vo.setHasLiked(0);  //是否点赞  0：未点 1:点赞
                }
                // 设置时间
                vo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));
                // 添加到list中
                voList.add(vo);
            }
        }
        //返回
        pageResult.setItems(voList);
        return pageResult;
    }


    //查询推荐状态
    public PageResult<MomentVo> queryRecommendPublishList(int page, int pagesize) {
        //获取登录用户的id
        Long userId = UserHolder.getUserId();
        //2、调用api完成分页查询   publish对象
        PageResult result = publishApi.findRecommendPublish(page, pagesize, userId);
        //3、获取publish列表
        List<Publish> items = (List<Publish>) result.getItems();
        //4、一个publish构造成一个Movements
        List<MomentVo> list = new ArrayList<>();
        if(items != null) {
            for (Publish item : items) {
                MomentVo vo = new MomentVo();
                UserInfo userInfo = userInfoApi.findByUserId(item.getUserId());
                if(userInfo != null) {
                    BeanUtils.copyProperties(userInfo,vo);
                    if(userInfo.getTags() != null) {
                        vo.setTags(userInfo.getTags().split(","));
                    }
                }
                BeanUtils.copyProperties(item, vo);
                vo.setId(item.getId().toHexString());
                vo.setCreateDate(RelativeDateFormat.format(new Date(item.getCreated())));
                String key1 = "publish_like_" + userId+"_" + vo.getId();
                if(redisTemplate.hasKey(key1)){
                    vo.setHasLiked(1);  //是否点赞  0：未点 1:点赞
                }
                else
                {
                    vo.setHasLiked(0);  //是否点赞  0：未点 1:点赞
                }
                vo.setImageContent(item.getMedias().toArray(new String[]{}));
                vo.setDistance("50米");
                list.add(vo);
            }
        }
        //5、构造返回值
        result.setItems(list);
        return result;
    }


    //查询我的动态
    public PageResult<MomentVo> queryMyAlbum(int page, int pagesize, Long userId) {
        //调用API
        PageResult result=publishApi.findMyAlbum(page,pagesize,userId);
        //获取所有的动态详情
        List<Publish> items =(List<Publish>) result.getItems();
        //循环遍历
        List<MomentVo>list=new ArrayList<MomentVo>();
        for (Publish item : items) {
            //创建MomentVo
            MomentVo vo=new MomentVo();
            //查询用户明细
            UserInfo userInfo=userInfoApi.findByUserId(item.getUserId());
            //组装数据
            if(userInfo !=null){
                BeanUtils.copyProperties(userInfo,vo);
                if(userInfo.getTags()!=null){
                    vo.setTags(userInfo.getTags().split(","));
                }
            }
            BeanUtils.copyProperties(item, vo);
            vo.setId(item.getId().toHexString());
            vo.setCreateDate(RelativeDateFormat.format(new Date(item.getCreated())));
            String key1 = "publish_like_" + userId+"_" + vo.getId();
            if(redisTemplate.hasKey(key1)){
                vo.setHasLiked(1);  //是否点赞  0：未点 1:点赞
            }
            else
            {
                vo.setHasLiked(0);  //是否点赞  0：未点 1:点赞
            }
            vo.setImageContent(item.getMedias().toArray(new String[]{}));
            vo.setDistance("50米");
            list.add(vo);
        }
        result.setItems(list);
        return result;
    }


    //动态详情
    public MomentVo queryById(String publishId) {
        //1，调用api查询动态详情
        Publish publish=publishApi.findById(publishId);
        //2，创建vo
        MomentVo momentVo=new MomentVo();
        //3，查询用户详情
        UserInfo userInfo=userInfoApi.findByUserId(publish.getUserId());
        Long userId = publish.getUserId();
        //4，构造数据
        if(userInfo!=null){
            BeanUtils.copyProperties(publish ,momentVo);
            if(userInfo.getTags()!=null){
                momentVo.setTags(userInfo.getTags().split(","));
            }
        }
        BeanUtils.copyProperties(publish,momentVo);
        momentVo.setId(publish.getId().toHexString());
        momentVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));
        momentVo.setHasLiked(0); //是否点赞  0：未点 1:点赞
        momentVo.setHasLoved(0); //是否点赞  0：未点 1:点赞
        momentVo.setImageContent(publish.getMedias().toArray(new String[0]));
        momentVo.setDistance("100米");
        return momentVo;
    }


    //谁看过我
    public List<VisitorVo> queryVisitors() {
        Long userId = UserHolder.getUserId();
        //1,从redis中获取上次的访问时间
        String key="visitors_time_"+userId;
        String time = (String) redisTemplate.opsForValue().get(key);
        //创建访问者集合
        List<Visitor>visitorList=new ArrayList<>();
        if(StringUtils.isNotEmpty(time)){
            //2,如果redis有时间数据，获取访问列表
            visitorList=visitorApi.queryVisitors(time,userId);
        }else {
            //3,没有数据，查询所有访客记录前五条
            visitorList=visitorApi.queryVisitors(userId);
        }
        //4,将访问时间记录到redis中
        redisTemplate.opsForValue().set(key,System.currentTimeMillis()+"");
        //5,返回vo
        List<VisitorVo> visitorVoList=new ArrayList<>();
        if(visitorList!=null&&visitorList.size()>0){
            for (Visitor visitor : visitorList) {
                VisitorVo visitorVo=new VisitorVo();
                //根据用户id查询用户信息
                UserInfo userInfo=userInfoApi.findByUserId(visitor.getUserId());//来访问的用户id
                BeanUtils.copyProperties(userInfo,visitorVo);
                //设置，补全
                visitorVo.setTags(StringUtils.split(userInfo.getTags(),","));
                visitorVo.setFateValue(visitor.getScore().intValue());//缘分值
                visitorVoList.add(visitorVo);
            }
        }
        return visitorVoList;
    }
}
